package com.lensong.statistic.aspect;

import com.lensong.statistic.annotation.StatisticRtCost;
import com.lensong.statistic.config.StatisticConfigProperties;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * Copyright （c）. All rights reserved.
 *
 * @author len.song
 * @date 2022/10/31
 */
@Component
@Aspect
@Slf4j
public class StatisticRtCostAspect {
    @Resource
    private StatisticConfigProperties statisticConfigProperties;


    @Pointcut("@annotation(com.lensong.statistic.annotation.StatisticRtCost)")
    public void point(){

    }

    @Around(value = "point()")
    public Object assertAround(ProceedingJoinPoint proceedingJoinPoint){
        Class<?> aClass = proceedingJoinPoint.getTarget().getClass();
        String methodName = proceedingJoinPoint.getSignature().getName();
        Class[] parameterTypes = ((MethodSignature) proceedingJoinPoint.getSignature()).getParameterTypes();
        //获取请求参数
        Object[] args = proceedingJoinPoint.getArgs();
        Object proceed = null;
        try {
            Method method = aClass.getMethod(methodName, parameterTypes);
            //方法名
            String name = method.getName();
            //获取方法上的注解
            StatisticRtCost annotation = method.getAnnotation(StatisticRtCost.class);
            String rtms = annotation.costGtRtms();
            long startTimeStamp = System.currentTimeMillis();
            //开始执行时间
            proceed = proceedingJoinPoint.proceed();
            //执行结束时间
            long endTimeStamp = System.currentTimeMillis();
            //TODO 埋点... 判断rt 埋点
            log.info("com.lensong.statistic.aspect.StatisticRtCostAspect.assertAround cost={}ms rt={}"
                    , (endTimeStamp - startTimeStamp), rtms);

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return proceed;
    }
}
